<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2>个人资料</h2>
      <p>管理您的个人信息和偏好设置</p>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：基本信息 -->
      <el-col :xs="24" :md="16">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="100px"
            size="large"
          >
            <el-form-item label="用户名">
              <el-input :value="userProfile?.username || ''" disabled />
            </el-form-item>
            
            <el-form-item label="邮箱">
              <el-input :value="userProfile?.email || ''" disabled>
                <template #suffix>
                  <el-tag v-if="userProfile?.is_verified" type="success" size="small">
                    已验证
                  </el-tag>
                  <el-tag v-else type="warning" size="small">
                    未验证
                  </el-tag>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="profileForm.nickname" placeholder="请输入昵称" />
            </el-form-item>
            
            <el-form-item label="个人简介" prop="bio">
              <el-input
                v-model="profileForm.bio"
                type="textarea"
                :rows="3"
                placeholder="介绍一下自己吧..."
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
            </el-form-item>
            
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="profileForm.gender">
                <el-radio label="male">男</el-radio>
                <el-radio label="female">女</el-radio>
                <el-radio label="other">其他</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                v-model="profileForm.birthday"
                type="date"
                placeholder="选择生日"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            
            <el-form-item label="所在地" prop="location">
              <el-input v-model="profileForm.location" placeholder="请输入所在地" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" :loading="loading" @click="updateProfile">
                保存修改
              </el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 密码修改 -->
        <el-card class="profile-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
            </div>
          </template>
          
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
            size="large"
          >
            <el-form-item label="当前密码" prop="old_password">
              <el-input
                v-model="passwordForm.old_password"
                type="password"
                placeholder="请输入当前密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="new_password">
              <el-input
                v-model="passwordForm.new_password"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirm_password">
              <el-input
                v-model="confirmPassword"
                type="password"
                placeholder="请确认新密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" :loading="passwordLoading" @click="changePassword">
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧：头像和统计信息 -->
      <el-col :xs="24" :md="8">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>头像</span>
            </div>
          </template>
          
          <div class="avatar-section">
            <div class="avatar-container">
              <el-avatar :size="120" :src="userStore.userAvatar" />
              <div class="avatar-overlay" @click="triggerAvatarUpload">
                <el-icon><Camera /></el-icon>
                <span>更换头像</span>
              </div>
            </div>
            
            <input
              ref="avatarInputRef"
              type="file"
              accept="image/*"
              style="display: none"
              @change="handleAvatarUpload"
            />
          </div>
        </el-card>

        <el-card class="profile-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>账户信息</span>
            </div>
          </template>
          
          <div class="info-section">
            <div class="info-item">
              <span class="label">注册时间：</span>
              <span class="value">{{ formatDate(userProfile?.created_at) }}</span>
            </div>
            <div class="info-item">
              <span class="label">最后登录：</span>
              <span class="value">{{ formatDate(userProfile?.last_login_at) }}</span>
            </div>
            <div class="info-item">
              <span class="label">登录次数：</span>
              <span class="value">{{ userProfile?.login_count || 0 }} 次</span>
            </div>
            <div class="info-item">
              <span class="label">账户状态：</span>
              <el-tag v-if="userProfile?.is_active" type="success">正常</el-tag>
              <el-tag v-else type="danger">已禁用</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElForm, ElMessage } from 'element-plus'
import { Camera } from '@element-plus/icons-vue'
import { useUserStore } from '../../store/modules/user'
import type { UserUpdate, UserPasswordChange } from '../../types/user'

const userStore = useUserStore()
const { userProfile } = userStore

const profileFormRef = ref<InstanceType<typeof ElForm>>()
const passwordFormRef = ref<InstanceType<typeof ElForm>>()
const avatarInputRef = ref<HTMLInputElement>()

const loading = ref(false)
const passwordLoading = ref(false)
const confirmPassword = ref('')

// 个人资料表单
const profileForm = reactive<UserUpdate>({
  nickname: '',
  bio: '',
  phone: '',
  gender: undefined,
  birthday: '',
  location: ''
})

// 密码修改表单
const passwordForm = reactive<UserPasswordChange>({
  old_password: '',
  new_password: ''
})

// 表单验证规则
const profileRules = {
  nickname: [
    { max: 100, message: '昵称不能超过100个字符', trigger: 'blur' }
  ],
  bio: [
    { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ]
}

// 验证确认密码
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请确认新密码'))
  } else if (value !== passwordForm.new_password) {
    callback(new Error('两次密码输入不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  old_password: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 50, message: '密码长度为6-50个字符', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 加载用户资料
const loadUserProfile = async () => {
  try {
    await userStore.fetchUserProfile()
    fillForm()
  } catch (error) {
    console.error('Load profile failed:', error)
  }
}

// 填充表单数据
const fillForm = () => {
  if (userProfile) {
    profileForm.nickname = userProfile.nickname || ''
    profileForm.bio = userProfile.bio || ''
    profileForm.phone = userProfile.phone || ''
    profileForm.gender = userProfile.gender
    profileForm.birthday = userProfile.birthday || ''
    profileForm.location = userProfile.location || ''
  }
}

// 更新个人资料
const updateProfile = async () => {
  if (!profileFormRef.value) return
  
  try {
    const valid = await profileFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    await userStore.updateProfile(profileForm)
    
  } catch (error) {
    console.error('Update profile failed:', error)
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  fillForm()
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return
    
    passwordLoading.value = true
    await userStore.changePassword(passwordForm)
    
    // 清空表单
    passwordForm.old_password = ''
    passwordForm.new_password = ''
    confirmPassword.value = ''
    
  } catch (error) {
    console.error('Change password failed:', error)
  } finally {
    passwordLoading.value = false
  }
}

// 触发头像上传
const triggerAvatarUpload = () => {
  avatarInputRef.value?.click()
}

// 处理头像上传
const handleAvatarUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }
  
  // 检查文件大小（5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return
  }
  
  try {
    await userStore.uploadAvatar(file)
  } catch (error) {
    console.error('Upload avatar failed:', error)
  }
  
  // 清空input
  target.value = ''
}

// 监听用户资料变化
watch(() => userProfile, fillForm, { deep: true })

// 组件挂载时加载数据
onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-header {
  margin-bottom: 30px;
}

.profile-header h2 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.profile-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: 600;
  color: #333;
}

.avatar-section {
  text-align: center;
  padding: 20px 0;
}

.avatar-container {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay span {
  font-size: 12px;
  margin-top: 5px;
}

.info-section {
  padding: 10px 0;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 0 10px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .label {
  color: #666;
  font-size: 14px;
}

.info-item .value {
  color: #333;
  font-weight: 500;
}

@media (max-width: 768px) {
  .profile-container {
    padding: 15px;
  }
  
  .el-form {
    padding: 0 10px;
  }
}
</style> 